/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.error;

import org.openislands.oi.constant.MessageCodeEnum;

public class LogicException extends RuntimeException {
    private final MessageCodeEnum responseMessageCode;
    private Object data;

    public LogicException(MessageCodeEnum responseMessageCode) {
        this(responseMessageCode, responseMessageCode.getMessage());
    }

    public LogicException(MessageCodeEnum responseMessageCode, String message) {
        this(null, responseMessageCode, message, null);
    }

    public LogicException(MessageCodeEnum responseMessageCode, String message, Object data) {
        this(null, responseMessageCode, message, data);
    }

    public LogicException(Throwable cause, MessageCodeEnum responseMessageCode, String message) {
        super(message, cause);
        this.responseMessageCode = responseMessageCode;
    }

    public LogicException(Throwable cause, MessageCodeEnum responseMessageCode, String message, Object data) {
        super(message, cause);
        this.data = data;
        this.responseMessageCode = responseMessageCode;
    }

    public Object getData() {
        return data;
    }

    public MessageCodeEnum getResponseMessageCode() {
        return responseMessageCode;
    }

    public static void isTrue(boolean expression, MessageCodeEnum messageCode) throws LogicException {
        isTrue(expression, messageCode, null);
    }

    public static void isTrue(boolean expression, MessageCodeEnum messageCode, String message) throws LogicException {
        if (!expression) {
            throw new LogicException(messageCode, message);
        }
    }

    public static void nonNull(Object object, MessageCodeEnum messageCode) throws LogicException {
        isTrue(object != null, messageCode);
    }

    public static void nonNull(Object object, MessageCodeEnum messageCode, String message) throws LogicException {
        isTrue(object != null, messageCode, message);
    }

    @Override
    public String toString() {
        return "LogicException{" +
                "responseMessageCode=" + responseMessageCode +
                ", data=" + data +
                "}, super: " + super.toString();
    }
}
